package com.imoblife.brainwavestus.customview;

import java.util.Timer;
import java.util.TimerTask;

import com.imoblife.brainwavestus.MainActivity;
import com.imoblife.brainwavestus.MainActivity.PlayState;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.oldMedia.MediaplayerFactory;
import com.imoblife.brainwavestus.oldMedia.MediaplayerFactory.Running;
import com.imoblife.brainwavestus.util.DebugUtil;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

public class PlayTimeWindows {

	MainActivity mainActivity;
	public TextView playtimeView;
	TextView playTimeDialogView;
	Button timeButton;
	long playtimes;

	public PlayTimeWindows(MainActivity mainActivity) {
		this.mainActivity = mainActivity;
		playtimeView = (TextView) mainActivity
				.findViewById(R.id.home_time_text);
		initTimeButton();
		getUserSetTime();
		playtimes = getRunningTime();
		if (playtimes <= 0) {
			playtimes = getUserSetTime();
		}
		if (getTimerSet()) {
			playtimeView.setText(getTimeFomat(playtimes));
			startTimerRuning();
		} else {
			playtimeView.setText(R.string.off);
		}

	}

	private void initTimeButton() {
		timeButton = (Button) mainActivity.findViewById(R.id.home_time_button);
		timeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog();
			}
		});
	}

	private void initPicker(TimePicker picker) {

		((View) picker.getParent()).setVisibility(View.VISIBLE);
		picker.setIs24HourView(true);

		int hour = (int) (getRunningTime() / (60 * 60 * 1000));
		int minute = (int) ((getRunningTime() / (60 * 1000)) % 60);
		System.out.println("hour=" + hour + "minute=" + minute);
		picker.setCurrentHour(hour);
		picker.setCurrentMinute(minute);

	}

	Dialog dialog;

	public void showDialog() {

		dialog = new Dialog(mainActivity, android.R.style.Theme_Light_Panel);
		dialog.setContentView(R.layout.timewindows);
		dialog.show();
		final CheckBox checkBox = (CheckBox) dialog
				.findViewById(R.id.settimebuttun);
		playTimeDialogView = (TextView) dialog.findViewById(R.id.timetext);
		final Running dialogRunning = new Running() {

			public void running(long current) {
				if (playTimeDialogView != null) {
					playTimeDialogView.setText(getTimeFomat(current));
				}
			}

			public void start() {
				// TODO Auto-generated method stub

			}

			public void pause() {
				// TODO Auto-generated method stub

			}

			public void stop() {

			}
		};
		try {
			mainActivity.mMediaplayerFactory
					.registerRunningListner(dialogRunning);
		} catch (Exception e) {
			// TODO: handle exception
		}

		final TimePicker tp = (TimePicker) dialog.findViewById(R.id.timePicker);

		Button close = (Button) dialog.findViewById(R.id.timerclose);

		close.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				dialog.cancel();
			}
		});

		if (getTimerSet()) {
			checkBox.setChecked(true);
			checkBox.setText(R.string.stop);
			((View) tp.getParent()).setVisibility(View.INVISIBLE);
			playTimeDialogView.setVisibility(View.VISIBLE);
			playTimeDialogView.setText(getTimeFomat(playtimes));
			playtimeView.setText(getTimeFomat(playtimes));
		} else {
			checkBox.setChecked(false);
			checkBox.setText(R.string.start);
			initPicker(tp);
			playTimeDialogView.setVisibility(View.INVISIBLE);
		}

		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				tp.clearFocus();

				if (isChecked) {
					int hour = tp.getCurrentHour();
					int minute = tp.getCurrentMinute();
					long tmp = hour * 60 * 60 * 1000 + minute * 60 * 1000;
					if (tmp < 1 * 60 * 1000) {
						tp.setCurrentMinute(1);
						tmp = 1 * 60 * 1000;
						Toast.makeText(mainActivity, R.string.time_warn,
								Toast.LENGTH_LONG).show();
						checkBox.setChecked(false);
						return;
					}
					checkBox.setText(R.string.stop);
					setRunningTimer(tmp);

					playtimes = tmp;
					playTimeDialogView.setText(getTimeFomat(playtimes));
					playtimeView.setText(getTimeFomat(playtimes));

					startTimerRuning();
					saveTimerset(true);
					((View) tp.getParent()).setVisibility(View.INVISIBLE);
					playTimeDialogView.setVisibility(View.VISIBLE);
				} else {
					saveTimerset(false);
					checkBox.setText(R.string.start);
					initPicker(tp);
					playTimeDialogView.setVisibility(View.INVISIBLE);
					setTimerRuningTime(-1);
					playtimeView.setText(R.string.off);

				}

			}
		});
		dialog.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {

				try {
					mainActivity.mMediaplayerFactory
							.unregisterRunningListner(dialogRunning);
					playTimeDialogView = null;
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		});
	}

	private void saveTimerset(boolean isSet) {

		SharedPreferences preferences = mainActivity.getSharedPreferences(
				"SetTimer", 0);
		preferences.edit().putBoolean("SetTimer", isSet).commit();
	}

	public boolean getTimerSet() {

		SharedPreferences preferences = mainActivity.getSharedPreferences(
				"SetTimer", 0);
		return preferences.getBoolean("SetTimer", true);
	}

	public void startTimerRuning() {

		try {
			if (mainActivity.mMediaplayerFactory.getBackgoundMediaPlayer()
					.getRunningTime() <= 0) {
				mainActivity.mMediaplayerFactory.getBackgoundMediaPlayer()
						.setRunningTime(playtimes);
				DebugUtil.debug("startTimerRuning", "");

			} else {
				playtimes = mainActivity.mMediaplayerFactory
						.getBackgoundMediaPlayer().getRunningTime();
				playtimeView.setText(getTimeFomat(playtimes));
				DebugUtil.debug("startTimerRuning", "");
			}

			mainActivity.mMediaplayerFactory.registerRunningListner(mRunning);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void resetPlayingTime() {

		try {
			playtimes = getUserSetTime();

			mainActivity.mMediaplayerFactory.getBackgoundMediaPlayer()
					.setRunningTime(playtimes);

			DebugUtil.debug("startTimerRuning", "���÷���ʱ��");

			mainActivity.mMediaplayerFactory.registerRunningListner(mRunning);

			if (playTimeDialogView != null) {
				playTimeDialogView.setText(getTimeFomat(playtimes));
			}

			playtimeView.setText(getTimeFomat(playtimes));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void setTimerRuningTime(long runing) {
		try {
			mainActivity.mMediaplayerFactory.getBackgoundMediaPlayer()
					.setRunningTime(runing);
			mainActivity.mMediaplayerFactory.registerRunningListner(mRunning);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	Running mRunning = new Running() {

		public void running(long current) {

			if (current <= 0) {
				resetPlayingTime();
			} else {
				playtimeView.setText(getTimeFomat(current));
				playtimes = current;
			}
		}

		public void start() {
			mainActivity.mPlayState = PlayState.start;
			mainActivity.playcheck.setChecked(true);
		}

		public void pause() {
			mainActivity.mPlayState = PlayState.pause;
			mainActivity.playcheck.setChecked(false);

		}

		public void stop() {
			mainActivity.mPlayState = PlayState.stop;
			mainActivity.playcheck.setChecked(false);
			if (getTimerSet()) {
				resetPlayingTime();
			}

		}
	};

	public long getRunningTime() {
		SharedPreferences preferences = mainActivity.getSharedPreferences(
				"SetTimer", 0);
		
		return preferences.getLong("runningTime", 30 * 60 * 1000);

	}

	public void setRunningTimer(long runningTimer) {
		SharedPreferences preferences = mainActivity.getSharedPreferences(
				"SetTimer", 0);
		preferences.edit().putLong("runningTime", runningTimer).commit();
		preferences.edit().putLong("setRunningTime", runningTimer).commit();

	}

	private long getUserSetTime() {

		SharedPreferences preferences = mainActivity.getSharedPreferences(
				"SetTimer", 0);

		if (preferences.getLong("setRunningTime", -2000) == -2000) {
			preferences.edit().putLong("setRunningTime", getRunningTime())
					.commit();
		}

		return preferences.getLong("setRunningTime", 0);

	}

	
	private String getTimeFomat(long time) {

		long s = getSec(time);
		long m = getMin(time);
		long h = gethour(time);

		String string = "";

		if (h < 10) {
			string += "0";
		}
		string += h + ":";
		if (m < 10) {
			string += "0";
		}
		string += m + ":";
		if (s < 10) {
			string += "0";
		}
		string += s;

		return string;
	}

	private long gethour(long time) {

		return time / (60 * 60 * 1000);
	}

	private long getMin(long time) {
		long tpm = time % (60 * 60 * 1000);
		return tpm / (60 * 1000);
	}

	private long getSec(long time) {

		return (((time % 3600000) % 60000) / 1000);
	}

}
